package cn.zhoutingrui.pethome.system.vcode.controller;

import cn.zhoutingrui.pethome.base.constants.BaseConstants;
import cn.zhoutingrui.pethome.system.user.domain.Wxuser;
import cn.zhoutingrui.pethome.system.user.service.IWxuserService;
import cn.zhoutingrui.pethome.system.vcode.domain.PhoneBind;
import cn.zhoutingrui.pethome.system.vcode.domain.PhoneLogin;
import cn.zhoutingrui.pethome.utils.AjaxResultUtil;
import cn.zhoutingrui.pethome.utils.SendMessage;
import cn.zhoutingrui.pethome.utils.StrUtils;
import cn.zhoutingrui.pethome.utils.VerifyCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RequestMapping("/vcode")
@RestController
@Api(value = "获取验证码",description = "获取验证码")
public class VcodeController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${Message.Uid}")
    private String uid;
    @Value("${Message.Key}")
    private String key;
    @Autowired
    private IWxuserService wxuserService;

    @PostMapping("/getImgVCode")
    @ApiOperation("获取图片验证码")
    public AjaxResultUtil getImgVCode(@RequestBody HashMap<String,String> hashMap){
        try {
            String uuid = hashMap.get("key");
            //生成验证码
            String vcode = StrUtils.getRandomString(4);
            String img = VerifyCodeUtils.VerifyCode(100, 40, vcode);
            //将验证码存入redis
            redisTemplate.opsForValue().set(uuid,vcode, BaseConstants.TimeOut.STATE_EMAIL,TimeUnit.MINUTES);
            return AjaxResultUtil.success().setData(img);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResultUtil.fail().setMsg("网络异常");
        }
    }

    @PostMapping("/getPhoneVcode")
    @ApiOperation("获取手机验证码")
    public AjaxResultUtil getPhoneVcode(@RequestBody PhoneLogin phoneLogin){
        String phone = phoneLogin.getPhone();
        String imageCode = phoneLogin.getImageCode();
        String uuid = phoneLogin.getImageCodeKey();
        if (uuid==null){
            return AjaxResultUtil.fail().setMsg("非法访问");
        }
        if (phone==null){
            return AjaxResultUtil.fail().setMsg("手机号非法");
        }
        String o1 = (String) redisTemplate.opsForValue().get(uuid);
        if (redisTemplate.opsForValue().get(uuid)==null){
            return AjaxResultUtil.fail().setMsg("图形验证码已过期");
        }
        if (!imageCode.equals(o1)){
            return AjaxResultUtil.fail().setMsg("验证码输入错误");
        }
        return sendMsg(phone,BaseConstants.Suffix.STATE_PHONE,BaseConstants.Suffix.STATE_TIME,BaseConstants.TimeOut.STATE_PHONE);
    }

    private AjaxResultUtil sendMsg(String phone,String bindPhone,String bindTime,Long bindTimeOut) {
        //以手机号生成一个key,用来保存验证码
        String vcodeKey= phone +bindPhone;
        //以手机号生成一个key,用来保存当前时间
        String timeKey= phone +bindTime;
        //判断是否该手机号是否在3分钟内已获取短信验证码
        Long o = (Long) redisTemplate.opsForValue().get(timeKey);
        if (o==null){
            //在三分钟内未获取短信验证码,应该生成一个新验证码
            String randomString = StrUtils.getRandomString(6);
            //把验证码存入redis
            redisTemplate.opsForValue().set(vcodeKey,randomString,bindTimeOut, TimeUnit.MINUTES);
            //存入当前时间
            redisTemplate.opsForValue().set(timeKey,System.currentTimeMillis(),bindTimeOut, TimeUnit.MINUTES);
        }else {
            //三分钟内以获取验证码,判断获取时间是否小于60s
            long now = System.currentTimeMillis();
            if ((now-o)<60000){
                return AjaxResultUtil.fail().setMsg("请勿频繁获取");
            }else {
                String randomString2 = StrUtils.getRandomString(6);
                //把验证码存入redis
                redisTemplate.opsForValue().set(vcodeKey,randomString2,bindTimeOut, TimeUnit.MINUTES);
                //存入当前时间
                redisTemplate.opsForValue().set(timeKey,System.currentTimeMillis(),bindTimeOut, TimeUnit.MINUTES);
            }
        }
        //SendMessage.send(uid,key,phone,"您的验证码为"+redisTemplate.opsForValue().get(vcodeKey));
        System.out.println(redisTemplate.opsForValue().get(vcodeKey));
        return AjaxResultUtil.success().setMsg("验证码已发送");
    }

    @PostMapping("/bind")
    @ApiOperation(("账号绑定获取验证码"))
    public AjaxResultUtil getVcdoToBind(@RequestBody PhoneBind phoneBind){
        String phone = phoneBind.getPhone();
        if (phone==null||"".equals(phone.trim()))
            return AjaxResultUtil.fail().setMsg("手机号错误");
        String unionId = phoneBind.getUnionId();
        Wxuser wxuser = wxuserService.findByUnionid(unionId);
        if (wxuser==null)
            return AjaxResultUtil.fail().setMsg("非法访问,请重新扫码");
        //发送验证码
        return sendMsg(phone, BaseConstants.Suffix.BIND_PHONE, BaseConstants.Suffix.BIND_TIME, BaseConstants.TimeOut.BIND_PHONE);
    }

}
